package offer.linkedList;

/**
 * @author DengYuan2
 * @create 2021-02-22 19:55
 */
public class n_23 {
    public static void main(String[] args) {
        n_23 n = new n_23();
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        ListNode n6 = new ListNode(6);
        ListNode n7 = new ListNode(7);
        ListNode n8 = new ListNode(8);
        ListNode n9 = new ListNode(9);
        ListNode n10 = new ListNode(10);
        ListNode n11 = new ListNode(11);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        n6.next = n7;
        n7.next = n8;
        n8.next = n9;
        n9.next = n10;
        n10.next = n11;
        n11.next = n4;
        ListNode re = n.EntryNodeOfLoop(n1);
        //因为是环形的，所以不能直接输出，要用另外一个自己重写的toString方法
        System.out.println(re.toString2());
    }

    /**
     * 额-直接看了思想：https://www.cnblogs.com/qingyunzong/p/9143321.htmlhttps://www.cnblogs.com/yorkyang/p/10876604.html
     * 最好的是：快慢指针
     *
     * @param pHead
     * @return
     */
    public ListNode EntryNodeOfLoop(ListNode pHead) {
        if (pHead==null||pHead.next==null){
            return null;
        }
        ListNode slow = pHead;
        ListNode fast = pHead;
        //必须要先走一次才行，先while的话走不动
        do {
            slow = slow.next;
            fast = fast.next.next;
        } while (slow != fast);
        slow = pHead;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}
